import axios from "axios"

export default {
  namespaced: true,
  state() {
    return {
      list: []
    }
  },

  mutations: {
    updateList(state, payload) {
      state.list = payload
    },
    changebtn(state, data) {
      state.list.find(item => item.id === data.id).count = data.count
    }
  },
  actions: {
    async getList(context) {
      const res = await axios.get('http://localhost:3000/cart')
      context.commit('updateList', res.data)
    },
    async getcount(context, data) {
      await axios.patch(`http://localhost:3000/cart/${data.id}`, {
        count: data.count
      })
      context.commit('changebtn', {
        id: data.id,
        count: data.count
      })

    }
  },

  getters: {
    total(state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },
    totalprice(state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)

    }
  }
}